import { Message } from 'element-ui'
import request from '@/utils/request'

function getExcel(data, url, responseType) {
  return request({
    url: url,
    method: 'post',
    data,
    responseType: responseType
  })
}

/**
 * 表格导出
 * @param {Object} data 请求参数
 * @param {String} url 请求地址
 * @param {String} fileName 文件名
 * @param {String} msg 导出成功提示
 */
export function exportExcelOut({ data, url, responseType = 'blob', fileName, msg = '已按查询条件导出' } = {}) {
  if (fileName && fileName.indexOf('.xls') === -1) {
    fileName = fileName + '.xlsx'
  }
  getExcel(data, url, responseType).then(res => {
    const link = document.createElement('a')
    link.download = fileName || decodeURIComponent(res.headers['content-disposition'].replace('attachment;filename=', ''))
    const blob = new Blob([res.data])
    link.style.display = 'none'
    link.href = window.URL.createObjectURL(blob)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(link.href)
    Message({
      message: msg,
      type: 'success'
    })
  }).catch(e => {
    Message({
      message: '导出失败',
      type: 'error'
    })
  })
}
